package com.wbk.lotterysystemsystemservice.controller.biz;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wbk.lotterysystemsystemservice.common.bo.AdminLoginBO;
import com.wbk.lotterysystemsystemservice.common.dto.AdminLoginDTO;
import com.wbk.lotterysystemsystemservice.entity.SysUser;
import com.wbk.lotterysystemsystemservice.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import result.Result;
import tools.JWTUtil;

import static tools.JWTUtil.getUserNo;
import static tools.JWTUtil.verify;


@Component
public class AdminLoginBiz {

    @Autowired
    AdminService adminService;

    public Result<AdminLoginDTO> login(AdminLoginBO adminLoginBO) {
        SysUser user = adminService.getUser(adminLoginBO);
        if (user == null) {
            return new Result<>(100, "用户名和密码不匹配", null);
        }
        String token = JWTUtil.create(user.getUserNo());
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
        adminLoginDTO.setUsername(user.getUsername()).setToken(token);
        return new Result<>(200, "登录成功", adminLoginDTO);
    }

    public Result<AdminLoginDTO> token(String token) {
        if (StringUtils.isEmpty(token)) {
            return new Result<>(100, "没有token,请登录", null);
        }
        DecodedJWT jwt = null;
        try {
            jwt = verify(token);
        } catch (Exception e) {
            return new Result<>(100, "token异常或已过期", null);
        }
        if (jwt == null) {
            return new Result<>(100, "token异常或已过期", null);
        }
        Long userNo = getUserNo(jwt);
        if (userNo <= 0) {
            return new Result<>(100, "token异常或已过期", null);
        }
        SysUser user = adminService.getUserByUserNo(userNo);
        if (user == null) {
            return new Result<>(100, "没找到用户信息，请重试", null);
        }
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
        adminLoginDTO.setUsername(user.getUsername()).setToken(token);
        return new Result<>(200, "token正常", adminLoginDTO);
    }
}
